package com.qf.fmall2203.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmall2203.product.entity.Product;
import com.qf.fmall2203.product.entity.ProductComments;
import com.qf.fmall2203.product.mapper.ProductCommentsMapper;
import com.qf.fmall2203.product.service.IProductCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2203.user.entity.Users;
import com.qf.fmall2203.user.service.IUsersService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品评价  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2023-02-15
 */
@Service
public class ProductCommentsServiceImpl extends ServiceImpl<ProductCommentsMapper, ProductComments> implements IProductCommentsService {

    @Autowired
    IUsersService usersService;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public HashMap<String, Object> detailCommonts(Integer id, Integer pageNum, Integer limit) {

        // 1. 创建分页对象
        final Page<ProductComments> page = new Page<>(pageNum,limit);
        page(page,new QueryWrapper<ProductComments>().eq("product_id",id));

        final HashMap<String, Object> data = new HashMap<>();
        data.put("pageCount",page.getPages()); // 总页数
        data.put("count",page.getTotal()); // 总条数
        final List<ProductComments> records = page.getRecords();
        // 填充缺失的用户相关属性信息
        populate(records);

        data.put("list",records); // 当前页的数据

        return data;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public HashMap<String, Object> detailCommontscount(Integer id) {

        //1. 按照comm_type分组查询
        final List<Map<String, Object>> listMaps = listMaps(new QueryWrapper<ProductComments>().select("comm_type,COUNT(1) as count").eq("product_id", id).groupBy("comm_type"));

        //2. 遍历map获取各评价信息

        Long goodTotal = 0l;
        Long badTotal =0l;
        Long midTotal =0l;

        for (Map<String, Object> map : listMaps) {
            final Integer comm_type = (Integer) map.get("comm_type");
            if (comm_type.equals(1)){
                // 好评
                goodTotal = (Long) map.get("count");

            }else if(comm_type.equals(0)) {
                // 中评
                midTotal = (Long) map.get("count");
            }else {
                // 差评
                badTotal = (Long) map.get("count");
            }
        }

        // 总评价数
        Long total = goodTotal+badTotal+midTotal;

        // 好评率
        final String percent = BigDecimal.valueOf(goodTotal).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP).toString();

        final HashMap<String, Object> map = new HashMap<>();

        map.put("goodTotal",goodTotal);
        map.put("total",total);
        map.put("badTotal",badTotal);
        map.put("midTotal",midTotal);
        map.put("percent",percent);

        return map;
    }

    /**
     * 为list中的ProductComments对象填充缺失的用户信息
     * @param records
     */
    private void populate(List<ProductComments> records) {

        //1. List<ProductComments> ---> List<UserID>
        final List<String> userIdList = records.stream().map(productComments -> productComments.getUserId()).collect(Collectors.toList());

        //2. 查询所有相关的用户信息
        final List<Users> userList = usersService.list(new QueryWrapper<Users>().in("user_id", userIdList));

        //3. List<Users>  ---->  Map<UserID,Users>
        final Map<Integer, Users> usersMap = userList.stream().collect(Collectors.toMap(o -> o.getUserId(), u -> u));


        //4. 遍历records，填充缺失的信息
        for (ProductComments comments : records) {
            final String userId = comments.getUserId(); // 获取用户id
            final Users users = usersMap.get(Integer.valueOf(userId));
            comments.setUsername(users.getUsername());
            comments.setUserImg(users.getUserImg());
            comments.setNickname(users.getNickname());

        }


    }
}
